package com.bill.gaty.audrey.service.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZip{
List<String> fileList=new ArrayList<String>();
private   File inputFile  ;
private   File outPutFolder  ;

 
 
public UnZip(File inputFile, File outPutFolder) {
	super();
	this.inputFile = inputFile;
	this.outPutFolder = outPutFolder;
}
public UnZip(String inputFile, String outPutFolder) {
	this(new File(inputFile),new File(outPutFolder));
}
public UnZip(File inputFile) {
	this(inputFile,new File(""));
}
public UnZip(String inputFile) {
	this(new File(inputFile));
}
public boolean isZip(){
	return inputFile.getName().toLowerCase().endsWith(".zip");
}
public String getFirstFile(){
	return this.fileList.get(0);
}
public void unZipIt(){
	fileList.clear();
if(!isZip()){
	fileList.add(inputFile.getAbsolutePath());
	return;
}
 byte[] buffer = new byte[64000];

 try{

	//create output directory is not exists
	File folder = (this.outPutFolder);
	if(!folder.exists()){
		folder.mkdir();
	}

	//get the zip file content
	ZipInputStream zis = 
		new ZipInputStream(new FileInputStream(this.inputFile));
	//get the zipped file list entry
	ZipEntry ze = zis.getNextEntry();

	while(ze!=null){

	   String fileName = ze.getName();
       File newFile = new File(outPutFolder ,fileName);
this.fileList.add(newFile.getAbsolutePath());
            //create all non exists folders
        //else you will hit FileNotFoundException for compressed folder
        new File(newFile.getParent()).mkdirs();

        FileOutputStream fos = new FileOutputStream(newFile);             

        int len;
        while ((len = zis.read(buffer)) > 0) {
   		fos.write(buffer, 0, len);
        }

        fos.close();   
        ze = zis.getNextEntry();
	}

    zis.closeEntry();
	zis.close();

	System.out.println("Done");

}catch(IOException ex){
   ex.printStackTrace(); 
}
} 
}
